package com.feituan.core.persistence.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feituan.core.persistence.mapper.OrderMapper;
import com.feituan.core.persistence.mapper.TypeCouponsMapper;
import com.feituan.core.persistence.mapper.UserCouponMapper;
import com.feituan.core.persistence.mapper.UserMapper;
import com.feituan.core.persistence.service.IUserService;
import com.feituan.core.pojo.entity.*;
import com.feituan.core.pojo.request.UserReq;
import com.feituan.core.pojo.response.UserRes;
import com.feituan.core.pojo.response.page.PageData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xiaohu
 * @since 2024-05-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TypeCouponsMapper typeCouponsMapper;

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Override
    public PageData<UserRes> queryPage(UserReq request) {
        Page<User> page = this.lambdaQuery()
                .page(new Page<>(request.getPage(), request.getLimit()));
        List<User> records = page.getRecords();

        List<UserRes> userResList = new ArrayList<>();
        records.forEach(el -> {
            UserRes userRes = new UserRes();
            BeanUtils.copyProperties(el, userRes);
            // 查询用户订单 设置订单总金额及订单个数
            LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
            qw.eq(true, Order::getType, 0);
            qw.eq(true, Order::getUserId, el.getId());
            qw.eq(true, Order::getOrderStatus, 1);
            List<Order> orders = orderMapper.selectList(qw);
            if (CollectionUtils.isEmpty(orders)) {
                userRes.setOrderPriceTotal(BigDecimal.ZERO);
                userRes.setOrderNum(0);
            } else {
                BigDecimal reduce = orders.stream().map(Order::getOrderPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                userRes.setOrderPriceTotal(reduce);
                userRes.setOrderNum(orders.size());
            }
            userResList.add(userRes);

        });


        if (request.getOrderNumSort() != null && request.getOrderNumSort() == 1) {
            List<UserRes> sortedList = userResList.stream()
                    .sorted(Comparator.comparingInt(UserRes::getOrderNum))
                    .collect(Collectors.toList());
            return PageData.build(page.getCurrent(), page.getTotal(), sortedList);
        }
        if (request.getOrderNumSort() != null && request.getOrderNumSort() == 2) {
            List<UserRes> sortedList = userResList.stream()
                    .sorted(Comparator.comparingInt(UserRes::getOrderNum).reversed())
                    .collect(Collectors.toList());
            return PageData.build(page.getCurrent(), page.getTotal(), sortedList);
        }

        if (request.getOrderPriceSort() != null && request.getOrderPriceSort() == 1) {
            List<UserRes> sortedList = userResList.stream()
                    .sorted(Comparator.comparing(UserRes::getOrderPriceTotal))
                    .collect(Collectors.toList());
            return PageData.build(page.getCurrent(), page.getTotal(), sortedList);
        }

        if (request.getOrderPriceSort() != null && request.getOrderPriceSort() == 2) {
            List<UserRes> sortedList = userResList.stream()
                    .sorted(Comparator.comparing(UserRes::getOrderPriceTotal).reversed())
                    .collect(Collectors.toList());
            return PageData.build(page.getCurrent(), page.getTotal(), sortedList);
        }

        if (request.getLatestLoginTimeSort() != null && request.getLatestLoginTimeSort() == 1) {
            List<UserRes> sortedList = userResList.stream()
                    .sorted(Comparator.comparing(UserRes::getLatestLoginTime))
                    .collect(Collectors.toList());
            return PageData.build(page.getCurrent(), page.getTotal(), sortedList);
        }

        if (request.getLatestLoginTimeSort() != null && request.getLatestLoginTimeSort() == 2) {
            List<UserRes> sortedList = userResList.stream()
                    .sorted(Comparator.comparing(UserRes::getLatestLoginTime).reversed())
                    .collect(Collectors.toList());
            return PageData.build(page.getCurrent(), page.getTotal(), sortedList);
        }

        return PageData.build(page.getCurrent(), page.getTotal(), userResList);
    }

    @Override
    public User selectById(Long userId) {
        return this.getById(userId);
    }

    /**
     * 修改积分
     *
     * @param user user
     * @return
     */
    @Override
    public synchronized int updateIntegration(User user) {
        return this.getBaseMapper().updateById(user);
    }

    /**
     * 根据用户Id查询集星数量
     *
     * @param userId userId
     */
    @Override
    public int selectStarsByUserId(Long userId) {
        return userMapper.selectStarsByUserId(userId);
    }

    /**
     * 修改用户领取新用户礼包状态
     * @param userId userId
     */
    @Override
    public boolean judgeNewUser(Long userId, String type) {
        if (userMapper.selectNewUserActivity(userId) != 0) {
            throw new IllegalStateException("该用户已经领取");
        }
        TypeCoupons typeCoupons = typeCouponsMapper.selectByType(type);
        if (typeCoupons == null) {
            throw  new IllegalStateException("优惠卷不存在");
        }
        for (Coupons coupon : typeCoupons.getCoupons()) {
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setUserId(userId);
            userCoupon.setCouponId(coupon.getCouponId());
            userCoupon.setCouponStatus(0);
            userCoupon.setCreateTime(new Date());
            userCouponMapper.insert(userCoupon);
        }
        return userMapper.updateNewUserActivity(userId) > 0;
    }
}
